<template>
    <view>
        <view>
          <view v-show="isTip" @touchmove.stop.prevent="stopSlide">
            <view class="mask" @click="isTip=false"></view>
            <view class="tip">点击右上角分享符，分享有分销提成 ↑</view>
          </view>
        </view>
        <scroll-view :scroll-Y="true" :scroll-X="false">
            <swiper class="swiper" :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval" :duration="duration">
                <block v-for="(item, index) in goods.productPics" :key="index">
                    <swiper-item :data-id="item">
                        <image mode="scaleToFill" :src="item.productPic" v-if="goods.isVideo == 0" />
                        <video
                            mode="scaleToFill"
                            :src="item.productPic"
                            v-if="goods.isVideo == 1"
                            class="media"
                            :show-center-play-btn="true"
                            :enable-play-gesture="true"
                            controls
                            loop
                        />
                    </swiper-item>
                </block>
            </swiper>
            <view style="display:flex;">
                <view class="title">{{ goods.productTitle }}</view>
                <view class="price">￥{{ goods.productPrice }}</view>
                <view class="title" v-if="goods.productDiscount != null || goods.labelNames != null">
                    <text v-if="goods.productDiscount != null" style="display: inline-block; width: 100px">折扣：{{ goods.productDiscount }}</text>
                    <text v-if="goods.labelNames != null">{{ goods.labelNames }}</text>
                </view>
            </view>
            <view class="info">
                <text>{{ goods.productDesc }}</text>
            </view>
        </scroll-view>
        <view class="footer">
            <view class="footer_box">
                <text class="footer_num">购买数量</text>
                <view class="footer_select">
                    <label id="reduce" @tap="buyCountFun">-</label>
                    <text>{{ buyCount }}</text>
                    <label id="add" @tap="buyCountFun">+</label>
                </view>
            </view>
            <view class="footer_btn">
                <button class="weui-btn1" open-type="share" v-if="isLogin" @click="showShare">分销提成</button>
                <button class="weui-btn2" @tap="buyNow">立即购买</button>
            </view>
        </view>
    </view>
</template>

<script>
var config = require('../../config.js');
var http = require('../../utils/httpHelper.js');
var util = require('../../utils/util.js');
import wx from 'weixin-js-sdk';
export default {
    data() {
        return {
            userInfo: {},
            isLogin: false,
            indicatorDots: true,

            //是否显示面板指示点
            autoplay: true,

            //是否自动切换
            interval: 5000,

            //自动切换时间
            duration: 1000,

            //滑动时间
            buyCount: 1,

            goods: {
                productPics: [],
                isVideo: 0,
                productTitle: '',
                productPrice: '',
                productDiscount: '',
                labelNames: '',
                productDesc: ''
            },

            buyCount: '1',
            isTip: false
        };
    },
    onLoad: function (options) {
        var that = this;
        let userInfo = uni.getStorageSync('user');
        if (userInfo != null && userInfo != undefined && userInfo != {} && userInfo != '') {
            that.setData({
                isLogin: true,
                userInfo: userInfo
            });
        } else {
            uni.setStorageSync('inviteId', options.inviteId);
        }
        var id = options.id;
        that.getGoodsInfo(id);
        setTimeout(()=>{
            this.share();
        },2000)
    },
    onShow: function () {
        let userInfo = uni.getStorageSync('user');
        if (userInfo != null && userInfo != undefined && userInfo != {} && userInfo != '') {
            this.setData({
                isLogin: true,
                userInfo: userInfo
            });
        }
    },
    mounted(){
        uni.setStorage({
            key: 'WxCodeUrl',
            data:location.href
        });
    },
    methods: {
        getGoodsInfo: function (id) {
            var curUserId = 0;
            if (this.userInfo.userId) {
              curUserId = this.userInfo.userId;
            }
            var that = this;
            var data = {
                id: id,
                userId: curUserId
            };
            http.httpGet(config.clubApi.getProductInfo, data, function (res) {
                if (res.code == '200') {
                    var goods = res.data;
                    that.setData({
                        goods: goods
                    });
                }
            });
        },

        buyCountFun: function (e) {
            var id = e.currentTarget.id;
            var count = this.buyCount;
            if (id == 'add') {
                count = count > 0 ? count + 1 : 1;
            } else {
                count = count > 0 ? count - 1 : 0;
            }
            this.setData({
                buyCount: count
            });
            this.buyNow('');
        },

        buyNow: function (e) {
            if (this.isLogin && uni.getStorageSync('user')) {
                var count = this.buyCount;
                count = count > 0 ? count : 1;
                var goods = this.goods;
                //取出订单商品
                goods = {
                    id: goods.id,
                    shopId: goods.shopId,
                    name: goods.productTitle,
                    img: goods.productPic,
                    price: goods.productPrice,
                    discount: goods.productDiscount,
                    buycount: parseInt(count)
                };                
                try {
                    var allGoods = uni.getStorageSync('shoppingcar');
                    if (allGoods == '') {
                        allGoods = [];
                    }
                    //检查订单是否有此商品
                    var hasCount = 0;
                    for (var i = 0; i < allGoods.length; i++) {
                        var temp = allGoods[i];
                        if (temp.id == goods.id) {
                            hasCount = temp.buycount;
                            allGoods.splice(i, 1);
                            break;
                        }
                    }
                    goods.buycount = goods.buycount + hasCount;
                    allGoods.push(goods);
                    uni.setStorageSync('shoppingcar', allGoods);
                } catch (m) {
                    console.log('CatchClause', m);
                    console.log('CatchClause', m);
                    console.log('立即购买失败!');
                }
                if (e != '') {
                    uni.navigateTo({
                      url: '/pages/shoppingcar/index'
                    });
                }
            } else {
                uni.switchTab({
                    url: '/pages/user/index'
                });
            }
        },
        getSignUrl(){
            var signLink = ''
            var ua = navigator.userAgent.toLowerCase();
            if (/iphone|ipad|ipod/.test(ua)) {
                signLink =uni.getStorageSync('WxCodeUrl');
                if(!signLink)signLink = location.href
            } else {
                signLink = location.href
            }
            return signLink;
        },
        showShare() {
          /*uni.showToast({
              title: '↑点击右上角分享符，分享有分销提成！',
              icon: 'none',
              mask: true,
              position: 'bottom',
              duration: 6000
          });*/
          this.isTip = true;
        },
        share(e) {
          var goods = this.goods;
          var curUrl = this.getSignUrl();
          var shareData = {
            title:goods.productTitle,
            desc:goods.productDesc,
            url:curUrl,
            image:goods.productPic
          };          
          //这是后端写的接口，需要用后端返回内容配置微信分享的参数
          uni.request({
            method: 'GET',
            url: config.BASE_URL + '/auth/getWXInterface',
            data: {
              url:curUrl,
              appid:config.APPID
            },
            header: {
                'U-TOKEN': uni.getStorageSync('user') ? uni.getStorageSync('user').token : '/pages/detail/index',
                "Content-Type": "application/x-www-form-urlencoded"
            },
            success: (res) => {
                if (res.statusCode == 401) {
                    uni.setStorageSync('user', null);
                }
                if (typeof cb == 'function') {
                    cb(res.data, '');
                }
                uni.hideNavigationBarLoading();
                if (res.statusCode == '200') {
                  const jsApiList=[
                    'checkJsApi', //检测接口权限	
                    'updateTimelineShareData',
                    'updateAppMessageShareData',
                    'openLocation',
                    'onMenuShareAppMessage', //老版本分享接口(注意这两个旧版本的必须要放的不然会有问题)
                    'onMenuShareTimeline', //老版本分享接口
                    'onMenuShareQQ', 
                    'onMenuShareQZone'
                  ];
                  wx.config({
                    debug:false,
                    appId:config.APPID,
                    timestamp:res.data.data.timestamp,
                    nonceStr:res.data.data.nonceStr,
                    signature:res.data.data.signature,					
                    jsApiList
                  });
                  wx.ready(() => {
                    var title = shareData.title
                    var imgUrl = shareData.image
                    var description = shareData.desc
                    var shareUrl = shareData.url
                    var tempParam = {
                      title: title,
                      desc: description,
                      link: shareUrl,
                      imgUrl: imgUrl,
                      success: (res) => {
                        console.log(res) 
                      },
                      cancel: function (res) {
                        console.log('分享失败', res)
                      },
                    }
                    if(wx.updateAppMessageShareData) {
                      wx.updateAppMessageShareData(tempParam);
                    } else {
                      wx.onMenuShareAppMessage(tempParam);
                    }
                    //if (shareData.index===0) {
                      //分享给朋友                      
                    /*}else if (shareData.index===1) {
                      //分享给朋友圈
                      if(wx.updateTimelineShareData) {
                        wx.updateTimelineShareData(tempParam);
                        } else {
                        wx.onMenuShareTimeline(tempParam);
                        }
                    }else if (shareData.index===2) {
                      wx.onMenuShareQQ(tempParam);
                    }else if (shareData.index===3) {
                      wx.onMenuShareQZone(tempParam);
                    }*/
                  });
                  wx.error(function(res){
                    console.log(res.errMsg);
                  })
                  // 判断客户端是否支持指定js的接口
                  wx.checkJsApi({
                    jsApiList,
                    success: function (res) {	       		
                      console.log('判断客户端支持js接口', res)
                    },
                  })
                }
            },
            fail: (err) => {
                if (typeof cb == 'function') {
                    cb(null, err.errMsg);
                }
                uni.hideNavigationBarLoading();
            }
          })
        }
    }
};
</script>
<style lang="scss">
@import './index.scss';
</style>
